package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2020/10/8 15:10
 **/
@Service
@Transactional
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper, ApUnlikesBehavior> implements ApUnLikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDto dto) {
        // 检查参数
        if(dto == null || dto.getArticleId() == null || (dto.getType()!=0 &&dto.getType()!=1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        // 查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询不喜欢记录是否存在
        ApUnlikesBehavior unlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, behaviorEntry.getId()));

        if (unlikesBehavior==null) {
            // 不存在新增
            unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setCreatedTime(new Date());
            unlikesBehavior.setEntryId(behaviorEntry.getId());
            unlikesBehavior.setType(dto.getType().intValue());
            save(unlikesBehavior);
        }else {
            // 存在修改
            unlikesBehavior.setType(dto.getType().intValue());
            updateById(unlikesBehavior);
        }
        return ResponseResult.okResult();
    }
}
